package com.qf.sturedis.controller;

import com.alibaba.fastjson.JSON;
import com.qf.sturedis.pojo.R;
import com.qf.sturedis.pojo.Student;
import com.qf.sturedis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//@RestController
//@RequestMapping("/stu")
public class StudentController {

    public static final String STU_CACHE_PREFIX = "stu:cache:id:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private StudentService studentService;

    @GetMapping("/{id}")
    public R findOne(@PathVariable("id") Integer id){
        Student stu = null;
        //引入缓存

        String key = STU_CACHE_PREFIX + id;
        //先查询缓存
        String valueJson = redisTemplate.opsForValue().get(key);
        //判断缓存是否存在
        if (!StringUtils.isEmpty(valueJson)){
            //有缓存：返回数据
            System.out.println("缓存中存在....");
            stu = JSON.parseObject(valueJson,Student.class);
        }else{
            //没有缓存: 查数据库 + 存入缓存 + 返回数据
            System.out.println("缓存中不存在，查询数据库....");
            stu = studentService.getById(id);
            if (stu != null){
                valueJson = JSON.toJSONString(stu);
                redisTemplate.opsForValue().set(key,valueJson);
            }else{
                //向缓存中存入一个空对象
                valueJson = JSON.toJSONString(new Student());
                redisTemplate.opsForValue().set(key,valueJson);
            }
        }

        //返回结果
        return R.success(stu);
    }
}
